﻿using System.Reactive.Linq;
using KinonekoSoftware.Studio.Models.Shells;
using KinonekoSoftware.Studio.Models.Shells;

namespace KinonekoSoftware.Studio.ViewModels
{
    partial class AppViewModel
    {
        private int  _TickBySeconds;
        private int  _Interval;
        private bool _Skip;

        #region TimeService

        
        public void UpdateTimeServiceConfiguration()
        {
            var setting = Ioc.Get<JuXiaoYouSetting>();
            _Interval = setting.AutoSave switch
            {
                AutoSavePeriod.Minute_10 => 600,
                AutoSavePeriod.Minute_15 => 900,
                AutoSavePeriod.Minute_20 => 1200,
                AutoSavePeriod.Minute_30 => 1800,
                _                        => 300,
            };

            _TickBySeconds %= _Interval;

            if(setting.AutoSave == AutoSavePeriod.Never)
            {
                _Skip = true;
            }
        }

        internal void InitializeTimeService()
        {
            //
            //
            UpdateTimeServiceConfiguration();
            
            //
            //
            Observable.Interval(TimeSpan.FromSeconds(2))
                      .ObserveOn(Scheduler)
                      .Subscribe(OnTimeServiceTicking)
                      .DisposeWith(Disposable);
        }

        private void OnTimeServiceTicking(long timestamp)
        {
            _TickBySeconds += 2;
            _TickBySeconds %= _Interval;

            if (_TickBySeconds == 0)
            {
                OnTimeServiceActivate();
            }
        }

#endregion
        
        private void OnTimeServiceActivate()
        {
            if (_Skip)
            {
                return;
            }


            OnAutoSave();
        }


        private async void OnAutoSave()
        {
            using (var session = await ((IBusyServiceEX)this).BeginSession("正在自动保存..."))
            {
                await session.Await(6);
                var concat = Inboard.Concat(Outboard);

                foreach (var viewModel in concat.OfType<ISaveSupport>())
                {
                    viewModel.Save();
                }
            
                Xplat.Debug($"{DateTime.Now} 完成自动保存。");
                await session.Await();
            }
        }
        
    }
}